package com.zhj.juc.demo6;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @PackageName:com.zhj.juc.demo6
 * @ClassName:Test3Semaphore
 * @auter: 朱慧杰
 * @date:2020/7/23 0023 22:32
 **/
public class Test3Semaphore {

    public static void main(String[] args) {

        // 线程数量 停车位 限流！
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                // acquire 得到  满的时候等待被释放 +1 控制最大线程数
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "抢到了车位！");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName() + "离开了车位！");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // release 释放 将当前信号量释放一 -1
                    semaphore.release();
                }

            },String.valueOf(i)).start();
        }

    }

}
